package com.tea.servlet;
import com.tea.util.DBUtil;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import com.tea.dao.ReviewDao;
import com.tea.entity.Review;

@WebServlet("/product-detail")
public class ProductDetailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws javax.servlet.ServletException, java.io.IOException {
        String productId = req.getParameter("productId");
        Map<String, Object> product = new HashMap<>();

        try (Connection conn = DBUtil.getConnection()) {
            if (productId == null || productId.isEmpty()) {
                req.setAttribute("errorMsg", "商品ID不能为空");
                req.getRequestDispatcher("/error.jsp").forward(req, resp);
                return;
            }
            String sql = "SELECT p.*, c.name AS categoryName FROM product p " +
                         "JOIN category c ON p.category_id = c.category_id WHERE p.product_id = ?";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setLong(1, Long.parseLong(productId));
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    product.put("id", rs.getInt("product_id"));
                    product.put("name", rs.getString("name"));
                    product.put("description", rs.getString("description"));
                    product.put("price", rs.getDouble("price"));
                    product.put("mainImage", rs.getString("main_image"));
                    product.put("weight", rs.getInt("weight"));
                    product.put("stock", rs.getInt("stock")); // 添加库存字段
                    product.put("categoryName", rs.getString("categoryName"));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("查询商品详情失败", e);
        }

        if (product.isEmpty()) {
            req.setAttribute("errorMsg", "商品不存在");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        } else {
            req.setAttribute("product", product);
            
            // 获取评论列表
            ReviewDao reviewDao = new ReviewDao();
            List<Review> comments = null;
            try {
                comments = reviewDao.getReviewsByProductId(Long.parseLong(productId));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            req.setAttribute("comments", comments);
            
            req.getRequestDispatcher("/product-detail.jsp").forward(req, resp);
        }
    }
}